package com.up360.rapidcalc.aerolite.model
{
    import com.up360.rapidcalc.aerolite.servers.AerolitesServer;
    
    import flash.display.DisplayObject;
    import flash.display.GradientType;
    import flash.display.Graphics;
    import flash.display.Shape;
    import flash.display.Sprite;
    import flash.events.TimerEvent;
    import flash.geom.Point;
    import flash.utils.Timer;

    /**
     * @author Tunie
     * @date   May 2, 2013
     * 激光束
     */
    public class LaserBeam extends GameElement
    {
        public static const DESCENDING:Number=0.3;
        /**
         *计时器 
         */
        private var _timer:Timer;
        /**
         *激光束数组 
         */
        private var _beans:Array;
        /**
         *锁 
         */
        private var _lock:Boolean;
        
        public function LaserBeam()
        {
            super();
            _beans=new Array();
            _lock=false;
            setupTimer();
        }
        
       
        
        override public function set ui(value:DisplayObject):void
        {
            checkUI();
            _ui = value;
        }
        
        /**
         *通过给定的两个点画一条直线 
         * @param p1
         * @param p2
         */
        public function showLine(p1:Point,p2:Point):void
        {
            var b_line:Shape=new Shape();
            var b_graphics:Graphics=b_line.graphics;
            b_graphics.lineStyle(5,0xffffff);
            b_graphics.lineGradientStyle(GradientType.LINEAR,[0xffcc00,0xff0000],[1,1],[127,255]);
            b_graphics.moveTo(p1.x,p1.y);
            b_graphics.lineTo(p2.x,p2.y);
            b_line.x=-p2.x;
            b_line.y=-p2.y;
            _beans.push(b_line);
            addChild(b_line);
            _timer.start();
        }
        
        private function setupTimer():void
        {
            _timer=new Timer(AerolitesServer.DELAY);
            _timer.addEventListener(TimerEvent.TIMER,timerTimer);
        }
        
        protected function timerTimer(event:TimerEvent):void
        {
            if(_lock) return;
            _lock=true;
            //
            var b_count:int=0;
            for each(var line:Shape in _beans)
            {
                line.alpha-=DESCENDING;
                if(line.alpha<=0)
                {
                    b_count++;
                    if(contains(line)) removeChild(line);
                }
            }
            _beans.splice(0,b_count);
            if(_beans.length==0) _timer.stop();
            //
            _lock=false;
        }
        
        override public function clear():void
        {
            //
            for each(var line:Shape in _beans)
            {
                if(contains(line)) removeChild(line);
                line=null;
            }
            _beans.splice(0,_beans.length);
        }
        
    }
}